<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;

class User extends Allow
{
    public function getindex()
    {
        //获取users表用户信息
        $users=Db::table("users")->select();
    	//加载后台用户模板
    	return $this->fetch("User/index",['users'=>$users]);
    }

    //添加
    public function getadd(){
        //加载用户添加模板
        return $this->fetch("User/add");
    }

    //执行添加
    public function postinsert(){
        $request=request();
        //获取密码
        $row=$request->only(['password','repassword']);
        //判断两次密码是否一致
        if($row['password']==$row['repassword']){
            //获取需要添加的值
            $data=$request->only(['username','password','email']);
            //给字段status赋值
            $data['status']=1;
            $preg='/^[a-zA-Z0-9_-]{4,16}$/';//用户名正则，4到16位（字母，数字，下划线，减号）    
            $preg2= '/^[a-zA-Z\d_]{4,}$/';//以数字字母下划线组成
            $preg3= '/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/';//邮箱的正则  
            if(preg_match($preg,$data['username']) && preg_match($preg2,$data['password']) && preg_match($preg3,$data['email'])){
                //判断是否添加成功
                if(Db::table('users')->insert($data)){
                    $this->success("添加成功","/adminuser/index");
                }else{
                    $this->error("添加失败","/adminuser/add");
                }
            }else{
                $this->error("用户名,密码或者邮箱格式不正确","/adminuser/add");
            }
        }else{
            $this->error("两次密码输入不正确","/adminuser/add");
        }
        

    }
    //删除
    public function getdelete(){
        $request=request();
        //获取id
        $id=$request->param('id');
        if(Db::table('users')->where('id',"{$id}")->delete()){
            $this->success("删除成功","/adminuser/index");
        }else{
            $this->error("删除失败","/adminuser/index");
        }
    }

    //修改
    public function getedit(){
        $request=request();
        //获取id
        $id=$request->param('id');
        //获取用户信息
        $info=Db::table('users')->where('id',"{$id}")->find();
        //获取添加页面
        return $this->fetch("User/update",['info'=>$info]);
    }

    //执行修改
    public function postupdate(){
        $request=request();
        //获取id
        $id=$request->param('id');
        //获取需要修改的值
        $data=$request->only(['username','password','email']);
        $data['status']=1;
        if(Db::table('users')->where('id',"{$id}")->update($data)){
            $this->success("修改成功","/adminuser/index");
        }else{
            $this->error("修改失败","/adminuser/edit");
        }
    }

}
